package com.authine.cloudpivot.ext.controller.workList;


import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.engine.api.model.organization.UserModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectCreatedModel;
import com.authine.cloudpivot.engine.api.model.runtime.WorkItemModel;
import com.authine.cloudpivot.engine.api.model.runtime.WorkflowInstanceModel;
import com.authine.cloudpivot.engine.enums.status.DataRowStatus;
import com.authine.cloudpivot.engine.enums.status.SequenceStatus;
import com.authine.cloudpivot.ext.Utils.CustomSchemaCode;
import com.authine.cloudpivot.ext.Utils.Utils;
import com.authine.cloudpivot.ext.service.CloudSqlService;
import com.authine.cloudpivot.web.api.controller.base.BaseController;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 公司往来单位基础信息
 */
@Slf4j
@RestController
@RequestMapping("/public/CompanyBasicInfoController")
public class CompanyBasicInfoController extends BaseController {

    @Autowired
    CloudSqlService sqlService;

    @RequestMapping("basicFinish")
    public void basicFinish(String bizId) {
        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject(CustomSchemaCode.CompanyBasicInfo, bizId);
        List<Map<String, Object>> list = (List<Map<String, Object>>) bizObject.get(CustomSchemaCode.CompanyBasicInfoDetail);

        String activeCode = "Activity16";
        String companyDeptCode = (String) bizObject.get("companyDeptCode");
        String responsibleDeptFNumber = (String) bizObject.get("responsibleDeptFNumber");
//        if (companyDeptCode.equals(responsibleDeptFNumber)) {
//            activeCode = "Activity5";
//        }
        String approval = "";
//        String approval = getFileBaseInfoWorkFlowApproval(bizObject, activeCode);
        for (Map<String, Object> map : list) {
            try {
                Map<String, Object> data = Utils.fileInfoBaseMap(map, approval);
                String id = existsBizObject(map);
                if (StringUtils.isNotBlank(id)) {
                    //基础信息表id
                    data.put("id", id);
                }
                BizObjectCreatedModel model = new BizObjectCreatedModel(CustomSchemaCode.CompanyBasicInfoBasic, data, false);
                model.setSequenceStatus(SequenceStatus.COMPLETED.name());
                id = getBizObjectFacade().saveBizObject(CustomSchemaCode.adminUserId, model, false);
                finishOrModifiyProcess(id);
            } catch (Exception e) {
                log.info("原始表数据:{}", JSONObject.toJSONString(map));
                e.printStackTrace();
            }
        }
    }


    @RequestMapping("basicToVoid")
    public void basicToVoid(String bizId) {
        String engineCode = "";
        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject(CustomSchemaCode.CompanyBasicInfoCancel, bizId);
        List<Map<String, Object>> list = (List<Map<String, Object>>) bizObject.get(CustomSchemaCode.CompanyBasicInfoDetailCancel);
        //获取审批人
        String activeCode = "Activity16";
        String companyDeptCode = (String) bizObject.get("companyDeptCode");
        String responsibleDeptFNumber = (String) bizObject.get("responsibleDeptFNumber");
        if (companyDeptCode.equals(responsibleDeptFNumber)) {
            activeCode = "Activity5";
        }

        String approval = getFileBaseInfoWorkFlowApproval(bizObject, activeCode);
        for (Map<String, Object> map : list) {
            try {
                String id = existsBizObject(map);
                //判断是否已存在，如果不存在，放弃这条数据，直接跳过此次循环
                if (StringUtils.isBlank(id)) {
                    continue;
                }
                //获取数据
                Map<String, Object> data = Utils.fileInfoBaseMap(map, approval);
                data.put("id", id);
                BizObjectCreatedModel model = new BizObjectCreatedModel(CustomSchemaCode.CompanyBasicInfoBasic, data, false);
                model.setSequenceStatus(SequenceStatus.CANCELED.name());
                id = getBizObjectFacade().saveBizObject(CustomSchemaCode.adminUserId, model, false);
                //调用存储过程
                toVoidProcess(id);

                // 删除公司往来单位档案点检汇总记录
                Map<String,Object> relevanceMap= (Map<String, Object>) data.get("companyBasicInfoSelect");
                String displayCode = MapUtil.getStr(relevanceMap, "displayCode");
                log.info("displayName", MapUtil.getStr(relevanceMap, displayCode));
                String tableName1 = this.getBizObjectFacade().getTableName(CustomSchemaCode.COMPANY_UNIT_BASE);
                String deleteSql1 = "delete from "+tableName1+" where functionCode = "+MapUtil.getStr(relevanceMap, displayCode)+"";
                sqlService.update(deleteSql1);
            } catch (Exception e) {
                log.info("参数：{}", JSONObject.toJSONString(map));
                e.printStackTrace();
            }
        }
    }


    /**
     * 财务 新增
     */
    @RequestMapping("financialFinish")
    public void financialFinish(String bizId) {
        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject(CustomSchemaCode.CompanyFinancial, bizId);
        List<Map<String, Object>> list = (List<Map<String, Object>>) bizObject.get(CustomSchemaCode.CompanyFinancialDetail);
        String activeCode = "Activity16";
        String companyDeptCode = (String) bizObject.get("companyDeptCode");
        String responsibleDeptFNumber = (String) bizObject.get("responsibleDeptFNumber");
        if (companyDeptCode.equals(responsibleDeptFNumber)) {
            activeCode = "Activity13";
        }
        String approval = getFileBaseInfoWorkFlowApproval(bizObject, activeCode);
        for (Map<String, Object> map : list) {
            try {
                Map<String, Object> data = Utils.fileInfoBaseMap(map, approval);
                String basicId = MapUtils.getString(map, "basicId", "");
                // 1 保存财务基础信息表
                String cwBasicId = saveToCompany(data, SequenceStatus.COMPLETED.name(), CustomSchemaCode.CompanyFinancialBasic);
                // 2 保存公司基础信息表中子表
                // 先查询基础表数据
                BizObjectCreatedModel basicModelS = getBizObjectFacade().getBizObject(CustomSchemaCode.CompanyBasicInfoBasic, basicId);
                Map<String, Object> basicModel = basicModelS.getData();
                List<Map<String, Object>> cwList = (List<Map<String, Object>>) basicModel.get(CustomSchemaCode.CompanyFinancialDetailTotal);
                cwList = cwList == null ? new ArrayList<>() : cwList;

                boolean flag = true;//是否向财务子表中新增数据
                for (Map<String, Object> cwMap : cwList) {
                    String cwMapId = (String) cwMap.get("id");
                    Map<String, Object> companyFinancialInfo = (Map<String, Object>) cwMap.get("companyFinancialInfo");
                    String companyFinancialInfoId = (String) companyFinancialInfo.get("id");
                    if (cwBasicId.equals(companyFinancialInfoId)) {
                        //说明此条财务信息已经存在于该公司的公司往来单位基础信息基础表的财务子表
                        cwMap.put("recordStatus", "有效数据");
                        cwMap.put("rowStatus", DataRowStatus.Modified);
                        data.put("cwBasicId", cwBasicId);
                        data.put("companyFinancialInfo", cwBasicId);
                        cwMap.putAll(data);
                        cwMap.put("id",cwMapId);
                        flag = false;
                    }
                }

                if (flag) {
                    data.put("recordStatus", "有效数据");
                    data.put("cwBasicId", cwBasicId);
                    data.put("rowStatus", DataRowStatus.Added);
                    data.put("companyFinancialInfo", cwBasicId);
                    cwList.add(data);
                }

                basicModel.put(CustomSchemaCode.CompanyFinancialDetailTotal, cwList);
                BizObjectCreatedModel model = new BizObjectCreatedModel(CustomSchemaCode.CompanyBasicInfoBasic, basicModel, false);
                model.setSequenceStatus(SequenceStatus.COMPLETED.name());
                getBizObjectFacade().saveBizObject(CustomSchemaCode.adminUserId, model, false);
                caiwuProcess(cwBasicId);
            } catch (Exception e) {
                log.info("原始表数据:{}", JSONObject.toJSONString(map));
                e.printStackTrace();
            }
        }
    }

    /**
     * 财务 作废
     */
    @RequestMapping("financialToVoid")
    public void financialToVoid(String bizId) {
        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject(CustomSchemaCode.CompanyFinancialCancel, bizId);
        List<Map<String, Object>> list = (List<Map<String, Object>>) bizObject.get(CustomSchemaCode.CompanyFinancialDetailCancel);
        //获取审批人
        String activeCode = "Activity16";
        String companyDeptCode = (String) bizObject.get("companyDeptCode");
        String responsibleDeptFNumber = (String) bizObject.get("responsibleDeptFNumber");
        if (companyDeptCode.equals(responsibleDeptFNumber)) {
            activeCode = "Activity13";
        }

        String approval = getFileBaseInfoWorkFlowApproval(bizObject, activeCode);
        for (Map<String, Object> map : list) {
            try {
                String basicId = MapUtils.getString(map, "basicId", "");
                //判断是否已存在，如果不存在，放弃这条数据，直接跳过此次循环
                if (StringUtils.isBlank(basicId)) {
                    continue;
                }
                //获取数据
                Map<String, Object> data = Utils.fileInfoBaseMap(map, approval);
                // 1 保存财务基础信息表
                String cwBasicId = saveToCompany(data, SequenceStatus.CANCELED.name(), CustomSchemaCode.CompanyFinancialBasic);
                // 2.保存基础表信息
//                String unit_id = MapUtils.getString(map, "unit_id", "");
                // 查询基础信息表
                BizObjectCreatedModel basicInfo = getBizObjectFacade().getBizObject(CustomSchemaCode.CompanyBasicInfoBasic, basicId);
                List<Map<String, Object>> cwList = (List<Map<String, Object>>) basicInfo.get(CustomSchemaCode.CompanyFinancialDetailTotal);
                cwList = cwList == null ? new ArrayList<>() : cwList;

                for (Map<String, Object> cwMap : cwList) {
                    String cwMapId = (String) cwMap.get("id");
                    Map<String, Object> companyFinancialInfo = (Map<String, Object>) cwMap.get("companyFinancialInfo");
                    String companyFinancialInfoId = (String) companyFinancialInfo.get("id");
                    if (cwBasicId.equals(companyFinancialInfoId)) {
                        cwMap.put("recordStatus", "作废数据");
                        cwMap.put("rowStatus", DataRowStatus.Modified);
                        data.put("cwBasicId", cwBasicId);
                        data.put("companyFinancialInfo", cwBasicId);
                        cwMap.putAll(data);
                        cwMap.put("id",cwMapId);
                    }
                }

                // 更新
                Map<String, Object> resultData = basicInfo.getData();
                resultData.put(CustomSchemaCode.CompanyFinancialDetailTotal, cwList);
                BizObjectCreatedModel model = new BizObjectCreatedModel(CustomSchemaCode.CompanyBasicInfoBasic, resultData, false);
                model.setSequenceStatus(SequenceStatus.COMPLETED.name());
                getBizObjectFacade().saveBizObject(CustomSchemaCode.adminUserId, model, false);
                //调用存储过程
                caiwuVoidProcess(cwBasicId);
            } catch (Exception e) {
                log.info("参数：{}", JSONObject.toJSONString(map));
                e.printStackTrace();
            }
        }
    }

    /**
     * 采购 有新增，但不需要作废流程
     */
    @RequestMapping("procurementFinish")
    public void procurementFinish(String bizId) {
        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject(CustomSchemaCode.CompanyProcurement, bizId);
        List<Map<String, Object>> list = (List<Map<String, Object>>) bizObject.get(CustomSchemaCode.CompanyProcurementDetail);
        String activeCode = "Activity16";
        String companyDeptCode = (String) bizObject.get("companyDeptCode");
        String responsibleDeptFNumber = (String) bizObject.get("responsibleDeptFNumber");
        if (companyDeptCode.equals(responsibleDeptFNumber)) {
            activeCode = "Activity13";
        }
        String approval = getFileBaseInfoWorkFlowApproval(bizObject, activeCode);
        for (Map<String, Object> map : list) {
            try {
                Map<String, Object> data = Utils.fileInfoBaseMap(map, approval);
                data.remove("approval", approval);
                data.put("approvalCG", approval);
                String id = existsBizObject(map);
                if (StringUtils.isNotBlank(id)) {
                    //基础信息表id
                    data.put("id", id);
                }
                BizObjectCreatedModel model = new BizObjectCreatedModel(CustomSchemaCode.CompanyBasicInfoBasic, data, false);
                model.setSequenceStatus(SequenceStatus.COMPLETED.name());
                id = getBizObjectFacade().saveBizObject(CustomSchemaCode.adminUserId, model, false);
                procurementProcess(id);
            } catch (Exception e) {
                log.info("原始表数据:{}", JSONObject.toJSONString(map));
                e.printStackTrace();
            }
        }
    }

    /**
     * 销售 有新增，但不需要作废流程
     */
    @RequestMapping("salesFinish")
    public void salesFinish(String bizId) {
        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject(CustomSchemaCode.CompanySales, bizId);
        List<Map<String, Object>> list = (List<Map<String, Object>>) bizObject.get(CustomSchemaCode.CompanySalesDetail);
        String activeCode = "Activity16";
        String companyDeptCode = (String) bizObject.get("companyDeptCode");
        String responsibleDeptFNumber = (String) bizObject.get("responsibleDeptFNumber");
        if (companyDeptCode.equals(responsibleDeptFNumber)) {
            activeCode = "Activity13";
        }
        String approval = getFileBaseInfoWorkFlowApproval(bizObject, activeCode);
        for (Map<String, Object> map : list) {
            try {
                Map<String, Object> data = Utils.fileInfoBaseMap(map, approval);
                data.remove("approval", approval);
                data.put("approvalXS", approval);
                String id = existsBizObject(map);
                if (StringUtils.isNotBlank(id)) {
                    //基础信息表id
                    data.put("id", id);
                }
                BizObjectCreatedModel model = new BizObjectCreatedModel(CustomSchemaCode.CompanyBasicInfoBasic, data, false);
                model.setSequenceStatus(SequenceStatus.COMPLETED.name());
                id = getBizObjectFacade().saveBizObject(CustomSchemaCode.adminUserId, model, false);
                salesProcess(id);
            } catch (Exception e) {
                log.info("原始表数据:{}", JSONObject.toJSONString(map));
                e.printStackTrace();
            }
        }
    }

    /**
     * 判断是否已存在
     *
     * @return
     */
    private String existsBizObject(Map data) {
        String unitCode = (String) data.get("unitCode");
        String tableName = getBizObjectFacade().getTableName(CustomSchemaCode.CompanyBasicInfoBasic);
        StringBuilder sql = new StringBuilder("select id  from ").append(tableName).append(" as A where A.unitCode ='").append(unitCode).append("' ORDER BY createdTime desc limit 1");
        Map<String, Object> map = sqlService.getMap(sql.toString());
        return (String) map.get("id");
    }

    /**
     * ----公司往来单位基础信息
     * exec   SyncCompanySupp
     *
     * @param bizId
     * @comid nvarchar(100),            ----公司id
     * @suppcode nvarchar(100),            ----往来单位代码
     * @ManageDeptid nvarchar(100),        ----管理部门代码
     * @PosACode nvarchar(100),        ----岗A代码
     * @PosBCode nvarchar(100),        ----岗B代码
     * @ManagePerson nvarchar(100),        ----管理员
     * @Auditor nvarchar(100)        -----02.0100 张三
     */
    private void finishOrModifiyProcess(String bizId) {
        if (bizId == null) {
            log.info("数据为空，写入存储过程失败");
            return;
        }

        //编写sql
        String tableName = getBizObjectFacade().getTableName(CustomSchemaCode.CompanyBasicInfoBasic);
        StringBuilder sql = new StringBuilder("SELECT * from ")
                .append(tableName).append(" where id ='")
                .append(bizId).append("';");
        //查询到入参
        Map<String, Object> map = sqlService.getMap(sql.toString());
        log.info("入参map={}", map);

        String company = MapUtils.getString(map, "company", "");
        String unitCode = MapUtils.getString(map, "unitCode", "");
        String responsibleDeptFid = MapUtils.getString(map, "responsibleDeptFNumber", "");
        String postACode = MapUtils.getString(map, "postACode", "");
        String postBCode = MapUtils.getString(map, "postBCode", "");
        String workContent = MapUtils.getString(map, "workContent", "");
        String approval = MapUtils.getString(map, "approval", "");

        String execSql = String.format("exec [HG_LINK].[hg].[dbo].SyncCompanySupp '%s','%s','%s','%s','%s','%s','%s'",
                company, unitCode, responsibleDeptFid, postACode, postBCode, workContent, approval);
        log.info("\n=============准备调用[公司往来单位基础信息]存储过程:{}", execSql);
        sqlService.execute(CloudSqlService.htEas, execSql);
        log.info("\n=============[公司往来单位基础信息]存储过程执行完成");
    }

    /**
     * ----公司往来单位基础信息 作废
     * exec   CompanySuppDisable
     *
     * @param bizId
     * @comid nvarchar(100),            ----公司id
     * @suppcode nvarchar(100),            ----往来单位代码
     */
    private void toVoidProcess(String bizId) {
        if (bizId == null) {
            log.info("数据为空，写入存储过程失败");
            return;
        }

        //编写sql
        String tableName = getBizObjectFacade().getTableName(CustomSchemaCode.CompanyBasicInfoBasic);
        StringBuilder sql = new StringBuilder("SELECT * from ")
                .append(tableName).append(" where id ='")
                .append(bizId).append("';");
        //查询到入参
        Map<String, Object> map = sqlService.getMap(sql.toString());
        log.info("入参map={}", map);

        String company = MapUtils.getString(map, "company", "");
        String unitCode = MapUtils.getString(map, "unitCode", "");

        String execSql = String.format("exec [HG_LINK].[hg].[dbo].CompanySuppDisable '%s','%s'",
                company, unitCode);
        log.info("\n==========准备调用[公司往来单位基础信息作废]存储过程:{}", execSql);
        sqlService.execute(CloudSqlService.htEas, execSql);
        log.info("\n=============[公司往来单位基础信息作废]存储过程执行完成");
    }

    /**
     * -------   公司往来单位财务信息
     * exec   SyncComSuppFaInfo
     *
     * @comid nvarchar(100),                ----公司id
     * @suppcode nvarchar(100),                ----往来单位代码
     * @bank nvarchar(100),                ----银行
     * @bankcode nvarchar(100),                ----银行代码
     * @account nvarchar(100),                ----账号
     * @taxno nvarchar(200),                ----税号
     * @address nvarchar(300),                ----地址
     * @accountname nvarchar(200),            ----开户名称
     * @invoice int,                        ----是否开票资料   1  是  0  否
     * @pay int,                        ----是否付款信息   1  是  0  否
     * @auditor nvarchar(100)                ----审批人 02.0100 张三
     */
    private void caiwuProcess(String bizId) {
        if (bizId == null) {
            log.info("数据为空，写入存储过程失败");
            return;
        }

        //编写sql
        String tableName = getBizObjectFacade().getTableName(CustomSchemaCode.CompanyFinancialBasic);
        StringBuilder sql = new StringBuilder("SELECT * from ")
                .append(tableName).append(" where id ='")
                .append(bizId).append("';");
        //查询到入参
        Map<String, Object> map = sqlService.getMap(sql.toString());
        log.info("入参map={}", map);

        String company = MapUtils.getString(map, "company", "");
        String unitCode = MapUtils.getString(map, "unitCode", "");
        String bank = MapUtils.getString(map, "bank", "");
        String bankCode = MapUtils.getString(map, "bankCode", "");
        String account = MapUtils.getString(map, "account", "");//账号
        String code = MapUtils.getString(map, "code", "");//税号 （统一社会信用代码）
        String mobile = MapUtils.getString(map, "mobile", "");
        String accountName = MapUtils.getString(map, "accountName", "");
        String invoice = MapUtils.getString(map, "invoice", "");
        invoice = "√".equalsIgnoreCase(invoice) ? "1" : "0";
        String payInfo = MapUtils.getString(map, "payInfo", "");
        payInfo = "√".equalsIgnoreCase(payInfo) ? "1" : "0";
        String approval = MapUtils.getString(map, "approval", "");

        String execSql = String.format("exec [HG_LINK].[hg].[dbo].SyncComSuppFaInfo '%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s'",
                company, unitCode, bank, bankCode, account, code, mobile, accountName, invoice, payInfo, approval);
        log.info("\n==========准备调用[公司往来单位财务信息]存储过程:{}", execSql);
        sqlService.execute(CloudSqlService.htEas, execSql);
        log.info("\n=============[公司往来单位财务信息]存储过程执行完成");
    }

    /**
     * ------	公司往来单位财务信息作废
     * exec    ComSuppFaInfoDisable
     *
     * @comid nvarchar(100),                ----公司id
     * @suppcode nvarchar(100),                ----往来单位代码
     * @account nvarchar(100),                ----账号
     * @auditor nvarchar(100)                ----审批人 02.0100 张三
     */
    private void caiwuVoidProcess(String bizId) {
        if (bizId == null) {
            log.info("数据为空，写入存储过程失败");
            return;
        }

        //编写sql
        String tableName = getBizObjectFacade().getTableName(CustomSchemaCode.CompanyFinancialBasic);
        StringBuilder sql = new StringBuilder("SELECT * from ")
                .append(tableName).append(" where id ='")
                .append(bizId).append("';");
        //查询到入参
        Map<String, Object> map = sqlService.getMap(sql.toString());
        log.info("入参map={}", map);

        String company = MapUtils.getString(map, "company", "");
        String unitCode = MapUtils.getString(map, "unitCode", "");
        String account = MapUtils.getString(map, "account", "");//账号
        String approval = MapUtils.getString(map, "approval", "");

        String execSql = String.format("exec [HG_LINK].[hg].[dbo].ComSuppFaInfoDisable '%s','%s','%s','%s'",
                company, unitCode, account, approval);
        log.info("\n==========准备调用[公司往来单位财务信息作废]存储过程:{}", execSql);
        sqlService.execute(CloudSqlService.htEas, execSql);
        log.info("\n=============[公司往来单位财务信息作废]存储过程执行完成");
    }

    /**
     * ----  公司往来单位采购信息
     * exec     SyncComSuppPurchaseInfo
     *
     * @company nvarchar(100),                ----公司id
     * @code nvarchar(100),                ----往来单位代码
     * @lvl nvarchar(20),                ----往来单位等级   1 一级  2  二级  3 三级 0  空
     * @PurCode nvarchar(100),                ----默认采购员代码
     * @contract nvarchar(100),                ----联系人
     * @post nvarchar(100),                ----职位
     * @tel nvarchar(100),                ----电话
     * @mobile nvarchar(100),                ----手机
     * @fax nvarchar(100),                ----传真
     * @mail nvarchar(100),                ----EMail
     * @addr nvarchar(100),                ----地址
     * @zipcode nvarchar(100),                ----邮编
     * @Auditor nvarchar(100)                ----审批人
     */
    private void procurementProcess(String bizId) {
        if (bizId == null) {
            log.info("数据为空，写入存储过程失败");
            return;
        }

        //编写sql
        String tableName = getBizObjectFacade().getTableName(CustomSchemaCode.CompanyBasicInfoBasic);
        StringBuilder sql = new StringBuilder("SELECT * from ")
                .append(tableName).append(" where id ='")
                .append(bizId).append("';");
        //查询到入参
        Map<String, Object> map = sqlService.getMap(sql.toString());
        log.info("入参map={}", map);

        String company = MapUtils.getString(map, "company", "");//公司id
        String unitCode = MapUtils.getString(map, "unitCode", "");//往来单位代码
        String gysdj = MapUtils.getString(map, "Dropdown1675401453503", "");//往来单位等级   1 一级  2  二级  3 三级 0  空
        String gysdjValue = "0";
        switch (gysdj) {
            case "Ⅰ":
                gysdjValue = "1";
                break;
            case "Ⅱ":
                gysdjValue = "1";
                break;
            case "Ⅲ":
                gysdjValue = "1";
                break;
        }
        String procurementCode = MapUtils.getString(map, "procurementCode", "");//默认采购员代码
        String procurementContract = MapUtils.getString(map, "procurementContract", "");//联系人
        String post = MapUtils.getString(map, "post", "");//职位
        String phone = MapUtils.getString(map, "phone", "");//电话
        String mobilePhone = MapUtils.getString(map, "mobilePhone", "");//手机
        String fix = MapUtils.getString(map, "fix", "");//传真
        String email = MapUtils.getString(map, "email", "");//EMail
        String contractAddress = MapUtils.getString(map, "contract_address", "");//地址
        String postCode = MapUtils.getString(map, "postCode", "");//邮编
        String approvalCG = MapUtils.getString(map, "approvalCG", "");//审批人

        String execSql = String.format("exec [HG_LINK].[hg].[dbo].SyncComSuppPurchaseInfo '%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s'",
                company, unitCode, gysdjValue, procurementCode, procurementContract, post, phone, mobilePhone,
                fix, email, contractAddress, postCode, approvalCG);
        log.info("\n=============准备调用[公司往来单位采购信息]存储过程:{}", execSql);
        sqlService.execute(CloudSqlService.htEas, execSql);
        log.info("\n=============[公司往来单位采购信息]存储过程执行完成");
    }

    /**
     * ----  公司往来单位销售信息
     * exec   SyncComSuppSaleInfo
     *
     * @comid nvarchar(100),                ----公司id
     * @code nvarchar(100),                ----往来单位代码
     * @custlvl nvarchar(50),                ----销售等级
     * @SaleAgent nvarchar(100),                ----默认销售员代码
     * @contract nvarchar(100),                ----联系人
     * @post nvarchar(100),                ----职位
     * @tel nvarchar(100),                ----电话
     * @mobile nvarchar(100),                ----手机
     * @fax nvarchar(100),                ----传真
     * @mail nvarchar(100),                ----EMAIL
     * @addr nvarchar(100),                ----地址
     * @zipcode nvarchar(100),                ----邮编
     * @deliveryaddr nvarchar(100),                ----送货地址
     * @auditor nvarchar(100)                ----审批人 02.0100 张三
     */
    private void salesProcess(String bizId) {
        if (bizId == null) {
            log.info("数据为空，写入存储过程失败");
            return;
        }

        //编写sql
        String tableName = getBizObjectFacade().getTableName(CustomSchemaCode.CompanyBasicInfoBasic);
        StringBuilder sql = new StringBuilder("SELECT * from ")
                .append(tableName).append(" where id ='")
                .append(bizId).append("';");
        //查询到入参
        Map<String, Object> map = sqlService.getMap(sql.toString());
        log.info("入参map={}", map);

        String company = MapUtils.getString(map, "company", "");//公司id
        String unitCode = MapUtils.getString(map, "unitCode", "");//往来单位代码
        String xsdj = MapUtils.getString(map, "Dropdown1675401453503X", "");//销售等级
        String xsdjValue = "0";
        switch (xsdj) {
            case "Ⅰ":
                xsdjValue = "1";
                break;
            case "Ⅱ":
                xsdjValue = "1";
                break;
            case "Ⅲ":
                xsdjValue = "1";
                break;
        }

        String procurementXCode = MapUtils.getString(map, "procurementXCode", "");//默认销售员代码
        String procurementContractX = MapUtils.getString(map, "procurementContractX", "");//联系人 文本
        String postX = MapUtils.getString(map, "postX", "");//职位
        String phoneX = MapUtils.getString(map, "phoneX", "");//电话

        String mobilePhoneX = MapUtils.getString(map, "mobilePhoneX", "");//手机
        String fixX = MapUtils.getString(map, "fixX", "");//传真
        String emailX = MapUtils.getString(map, "emailX", "");//EMAIL
        String addressX = MapUtils.getString(map, "addressX", "");//地址  联系地址
        String postCodeX = MapUtils.getString(map, "postCodeX", "");//邮编
        String shAddress = MapUtils.getString(map, "shAddress", "");//送货地址
        String approvalXS = MapUtils.getString(map, "approvalXS", "");//审批人 02.0100 张三

        String execSql = String.format("exec [HG_LINK].[hg].[dbo].SyncComSuppPurchaseInfo '%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s'",
                company, unitCode, xsdjValue, procurementXCode, procurementContractX, postX, phoneX,
                mobilePhoneX, fixX, emailX, addressX, postCodeX, shAddress, approvalXS);
        log.info("\n=============准备调用[公司往来单位销售信息]存储过程:{}", execSql);
        sqlService.execute(CloudSqlService.htEas, execSql);
        log.info("\n=============[公司往来单位销售信息]存储过程执行完成");
    }

    /**
     * 查询审批人,返回  员工号+姓名
     *
     * @param bizObject
     * @return
     */
    private String getFileBaseInfoWorkFlowApproval(BizObjectCreatedModel bizObject, String finalActivityCode) {
        WorkflowInstanceModel instanceModel = getWorkflowInstanceFacade().getByObjectId(bizObject.getId());
        List<WorkItemModel> workItems = getWorkflowInstanceFacade().getWorkItems(instanceModel.getId(), true);
        Optional<WorkItemModel> first = workItems.stream().filter(a -> a.getActivityCode().equals(finalActivityCode)).findFirst();
        String participant = null;
        if (first.isPresent()) {
            WorkItemModel workItemModel = first.get();
            participant = workItemModel.getParticipant();
        }
        if (participant == null) {
            participant = bizObject.getCreater().getId();
        }
        UserModel user = getOrganizationFacade().getUser(participant);
        return new StringBuilder(user.getEmployeeNo()).append("　").append(user.getName()).toString();
    }


    private String saveToCompany(Map<String, Object> map, String status, String formCode) {
        String account = MapUtils.getString(map, "account", "");//账号
        String unitCode = MapUtils.getString(map, "unitCode", "");//往来单位代码
        String companyNumber = MapUtils.getString(map, "companyNumber", "");//公司代码隐藏

        //编写sql
        String tableName = getBizObjectFacade().getTableName(CustomSchemaCode.CompanyFinancialBasic);
        StringBuilder sql = new StringBuilder("select id from ").append(tableName).append(" where companyNumber = '")
                .append(companyNumber).append("' and unitCode = '").append(unitCode)
                .append("' and account = '").append(account).append("';");
        //查询到入参
        Map<String, Object> data = sqlService.getMap(sql.toString());
        String id = MapUtils.getString(data, "id", "");//公司财务基础信息表id
        if (StringUtils.isNotBlank(id)) {
            map.put("id", id);
        }

        BizObjectCreatedModel model = new BizObjectCreatedModel(formCode, map, false);
        model.setSequenceStatus(status);
        id = getBizObjectFacade().saveBizObject(CustomSchemaCode.adminUserId, model, false);
        return id;
    }
}
